package com.ycg.biquge.interceptor;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import com.ycg.biquge.pojo.Chapter;
import org.apache.ibatis.cursor.Cursor;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.*;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.sql.CallableStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author YCG
 * @date 2024-05-03 10:35
 * @description 拦截章节表, 将content的base64字符串解压并且按换行符转换为句子列表
 */
@Intercepts({
        @Signature(
                type = ResultSetHandler.class,
                method = "handleResultSets",
                args = {Statement.class})
})
@Component("contentInterceptor")
public class ContentInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object result = invocation.proceed();
        if (result instanceof List<?> list) {
            for (Object o : list) {
                if (o instanceof Chapter chapter) {
                    String content = chapter.getContent();
                    // 获取数据首页时会查询该小说小的章节列表
                    if (StrUtil.isBlank(content)) break;
                    // 尝试解压content
                    unzip(chapter);
                    List<String> lines = Arrays.stream(chapter.getContent().split("\n"))
                            .filter(StrUtil::isNotBlank).map(String::strip).toList();
                    chapter.setList(lines);
                }
            }
        }
        return result;
    }

    /**
     * 解压content
     *
     * @param chapter 章节信息
     */
    private void unzip(Chapter chapter) {
        String content = chapter.getContent();
        if (content.contains("H4sIAAAAAAAA")) {
            // content为base64加密
            byte[] decode = Base64.decode(content);
            content = ZipUtil.unGzip(decode, CharsetUtil.UTF_8);
            chapter.setContent(content);
        }
    }
}
